package cn.edu.ctbu.demo.service;

import cn.edu.ctbu.demo.constant.REnum;
import cn.edu.ctbu.demo.dao.StudentRepository;
import cn.edu.ctbu.demo.entity.Student;
import cn.edu.ctbu.demo.exception.RException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StudentService {
    @Autowired
    public StudentRepository studentRepository;
    public List<Student> getAll(){
        return studentRepository.findAll();
    }

    /**
     * 新增学生
     * @param student
     * @return
     */
    public Student add(Student student){
        return studentRepository.save(student);
    }

    public Student findById(Integer id){
        return studentRepository.findById(id).orElse(null);
    }

    public Student update(Student student){
        return studentRepository.save(student);
    }

    public void delete(Integer id){
        studentRepository.deleteById(id);
    }

    @Transactional
    public void deleteByIds(List<Integer> ids){

        studentRepository.deleteByIds(ids);

    }

    public Student validateUsernameAndPassword(String sno, String password) throws Exception{
        List<Student> students=studentRepository.findBySno(sno);
        if(students.size()>0){
            Student student=students.get(0);
            if(student.getPassword().equals(password)){
                return student;
            }else{
                throw new RException(REnum.LOGIN_ERR);
            }
        }else{
            throw new RException(REnum.LOGIN_ERR);
        }
    }

    public Page<Student> getAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    }
    public Page<Student> getAll(Example<Student> example, Pageable pageable){
        return studentRepository.findAll(example,pageable);
    }
}
